let io;

const { registerEventHandlers } = require('./events');

function initSocket(server) {
  const socketIo = require('socket.io');
  io = socketIo(server, {
    cors: {
      origin: 'http://localhost:5173',
      methods: ['GET', 'POST'],
      credentials: true,
    },
  });

  io.use((socket, next) => {
    const token = socket.handshake.auth.token;
    if (!token) return next(new Error('Authentication error: missing token'));

    try {
      const config = require('../config/config');
      const jwt = require('jsonwebtoken');
      const decoded = jwt.verify(token, config.jwt.secret);
      socket.user = decoded;
      next();
    } catch (err) {
      return next(new Error('Authentication error: invalid token'));
    }
  });

  registerEventHandlers(io); // 统一注册事件
}

// 获取 io 实例
function getIo() {
  if (!io) {
    throw new Error('Socket.IO instance not initialized');
  }
  return io;
}

module.exports = {
  initSocket,
  getIo,
};